package com.fuershiye.woman.monitor.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fuershiye.woman.monitor.beans.Page;
import com.fuershiye.woman.monitor.beans.PageResult;
import com.fuershiye.woman.monitor.beans.Result;
import com.fuershiye.woman.monitor.beans.ViewBulletin;
import com.fuershiye.woman.monitor.beans.ViewContent;
import com.fuershiye.woman.monitor.constants.Massage;
import com.fuershiye.woman.monitor.model.Bulletin;
import com.fuershiye.woman.monitor.model.BulletinRead;
import com.fuershiye.woman.monitor.model.Content;
import com.fuershiye.woman.monitor.model.Department;
import com.fuershiye.woman.monitor.model.User;
import com.fuershiye.woman.monitor.service.BulletinReadService;
import com.fuershiye.woman.monitor.service.BulletinService;
import com.fuershiye.woman.monitor.service.ContentService;
import com.fuershiye.woman.monitor.service.UserService;
import com.fuershiye.woman.monitor.utils.ObjectUtil;
import com.google.common.collect.Lists;

/**
 * 通知公告
 * 
 * @author yongyongdong
 *
 */
@Controller
@RequestMapping(value = "/bulletin")
public class BulletinController {

	private static final Logger logger = LoggerFactory
			.getLogger(BulletinController.class);

	@Autowired
	BulletinService bulletinService;
	@Autowired
	ContentService contentService;
	@Autowired
	BulletinReadService bulletinReadService;
	@Autowired
	UserService userService;
	
//	@RequiresPermissions("bulletin:view")
    @RequestMapping(value="/view.do")
    public String view(String show){
    	
        return "bulletin/" + show;
        
    }

//	@RequiresPermissions("report:delete")
	@RequestMapping(value = "/delete.do")
	@ResponseBody
	public boolean delete(Long bid) {
		if(bid==null || bid ==0){
			return false;
		}
		Bulletin bulletin = bulletinService.get(bid);
		bulletin.setStatus(0);// 修改为已删除
		bulletinService.save(bulletin);
		return true;
	}
	
//	@RequiresPermissions("report:save")
	@RequestMapping(value = "/save.do")
	@ResponseBody
	public boolean save(HttpServletRequest request) {

		String bidPost = request.getParameter("bid");
		String contentPost = request.getParameter("content");
		String typePost = request.getParameter("type");
		String titlePost = request.getParameter("title");
		String resourcesPost = request.getParameter("resources");
		
		if(StringUtils.isBlank(contentPost) || StringUtils.isBlank(typePost) || StringUtils.isBlank(titlePost)){
			logger.error("content:"+contentPost+";type:"+typePost+";title:"+titlePost);
			return false;
		}
		
		int type = Integer.parseInt(typePost);
		long bid = 0L;
		if(StringUtils.isNotBlank(bidPost)){
			bid = Long.parseLong(bidPost);
		}
		
		boolean add = false;
		Bulletin bulletin = null;
		if (bid == 0) {
			bulletin = new Bulletin();
			add = true;
		} else {
			bulletin = bulletinService.get(bid);
			if (bulletin == null) {
				logger.error("BulletinController save, bulletin is null");
				return false;
			}
		}

		//先保存内容
		Content content = new Content();
		//原来已内容存在
		if(bulletin.getCid()!=null){
			content = contentService.get(bulletin.getCid());
			content.setInfo(contentPost);
			content.setMtime(new Date());
		}else{
			//原来不存在
			content.setCtime(new Date());
			content.setInfo(contentPost);
			content.setMtime(new Date());
			content.setStatus(0);
			content.setType(1);
		}
		contentService.save(content);
		logger.info(content.getId()+"cid");

		String uname = SecurityUtils.getSubject().getPrincipal() + "";
		if(StringUtils.isBlank(resourcesPost)){
			Department department = userService.getDepartIdByName(uname);
			if(department==null){
				logger.error("AreaController getSamePid,department is null, user name:{}", uname);
				return false;
			}
			resourcesPost = department.getName();
		}
		
		bulletin.setCid(content.getId());
		bulletin.setEditor(uname);
//		表示永不过期,null
//		bulletin.setExpire(null);
		bulletin.setLevel(0);
		bulletin.setMtime(new Date());
		bulletin.setResources(resourcesPost);
		bulletin.setStatus(1);
		bulletin.setTitle(titlePost);
		bulletin.setType(type);
		if(add){
			bulletin.setAuthor(uname);
			bulletin.setCtime(new Date());
		}
		bulletinService.save(bulletin);
		return true;
	}
	
    @SuppressWarnings({ "rawtypes", "unchecked" })
	//	@RequiresPermissions("bulletin:list")
	@RequestMapping(value = "/list.do")
	@ResponseBody
	public Result list(String title, Integer type, Integer page, Integer pageSize) {

    	if(type!=null && type!=0 && type!=1 && type!=2){
			return new Result(Massage.ERROR_PARAMETER);
    	}
    	if(type!=null && type==0){
    		type=null;
    	}
    	if(StringUtils.isBlank(title)){
    		title = null;
    	}
		Page pageObj = new Page(page, pageSize);
		
		User user = userService.getDByName(SecurityUtils.getSubject().getPrincipal()+"");
		if(user==null){
			logger.error("user is not exit!");
			return new Result(Massage.USER_IS_NULL);
		}
		
		List<Bulletin> bulletinList  = bulletinService.listByCondition(title, type, 1, pageObj);
		int count  = bulletinService.countByCondition(title, type, 1);
		List<Long> userAllBid = bulletinReadService.getAllBidByUid(user.getId());
		
		List<ViewBulletin> result = Lists.newArrayList();
		for (Bulletin bulletin : bulletinList) {
			result.add(ObjectUtil.turnBulletin2ViewBulletin(bulletin, userAllBid));
		}

		return new Result(Massage.SUCCESS, new PageResult(result, count));
	}
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    //	@RequiresPermissions("bulletin:list")
    @RequestMapping(value = "/content/info.do")
    @ResponseBody
    public Result getContentInfo(Long cid) {

    	if(cid==null||cid==0){
			return new Result(Massage.ERROR_PARAMETER);
    	}
		Content content = contentService.get(cid);
		if(content==null){
			return new Result(Massage.CONTENT_INFO_IS_NULL);
		}
		ViewContent viewContent = new ViewContent();
		viewContent.setId(content.getId());
		viewContent.setInfo(content.getInfo());
    	return new Result(Massage.SUCCESS, viewContent);
    }
    
    @SuppressWarnings({ "rawtypes"})
    //	@RequiresPermissions("bulletin:read")
    @RequestMapping(value = "/read.do")
    @ResponseBody
    public Result getShowPage(Long bid) {
    	
    	if(bid==null||bid==0){
    		return new Result(Massage.ERROR_PARAMETER);
    	}
    	
    	User user = userService.getDByName(SecurityUtils.getSubject().getPrincipal()+"");
    	if(user==null){
    		logger.error("user is not exit!");
    		return new Result(Massage.USER_IS_NULL);
    	}
    	
    	Bulletin bulletin = bulletinService.get(bid);
    	if(bulletin==null){
    		return new Result(Massage.CONTENT_IS_NULL);
    	}
    	BulletinRead bulletinRead = bulletinReadService.getByBidUid(bid, user.getId());
    	if(bulletinRead!=null){
    		bulletinRead.setRstatus(1);
    		bulletinRead.setRtime(new Date());
    	}else{
    		bulletinRead = new BulletinRead();
    		bulletinRead.setBid(bid);
    		bulletinRead.setCtime(new Date());
    		bulletinRead.setRstatus(1);
    		bulletinRead.setRtime(new Date());
    		bulletinRead.setStatus(0);
    		bulletinRead.setUid(user.getId());
    	}
    	bulletinReadService.save(bulletinRead);
    	
    	return new Result(Massage.SUCCESS);
    }

}
